package com.xh.amqp.service.impl;

import com.xh.amqp.domain.Book;
import com.xh.amqp.service.ISmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @Name BookService
 * @Description
 * @Author wen
 * @Date 2019-07-11
 */
@Service
@Slf4j
public class SmsServiceImpl implements ISmsService {

    @Autowired
    private AmqpAdmin amqpAdmin;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = {MQ_EMAIL_QUEUE})
    public void receive(Book book) {
        System.err.println(book.getClass());
        System.err.println(book);
    }

    @Override
    public void createEmailMQ(boolean flag) {
        log.info("======================== START初始化RabbitMQ的邮箱配置 >>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        if (flag) {
            log.info("---------------- 0.删除原有的{}交换机，及{}队列 ----------------", MQ_EMAIL_EXCHANGE, MQ_EMAIL_QUEUE);
            //--删除已有的--
            amqpAdmin.deleteExchange(MQ_EMAIL_EXCHANGE);
            amqpAdmin.deleteQueue(MQ_EMAIL_QUEUE);
        }
        //1.创建交换机
        amqpAdmin.declareExchange(new DirectExchange(MQ_EMAIL_EXCHANGE));
        log.info("---------------- 1.创建{}交换机 ----------------", MQ_EMAIL_EXCHANGE);
        //2.创建队列
        amqpAdmin.declareQueue(new Queue(MQ_EMAIL_QUEUE, true));
        log.info("---------------- 2.创建{}队列 ----------------", MQ_EMAIL_QUEUE);
        //3.绑定
        Binding binding = new Binding(MQ_EMAIL_QUEUE, Binding.DestinationType.QUEUE, MQ_EMAIL_EXCHANGE, MQ_EMAIL_ROUTINGKEY, null);
        log.info("---------------- 3.绑定{}交换机和{}队列 ----------------", MQ_EMAIL_EXCHANGE, MQ_EMAIL_QUEUE);
        amqpAdmin.declareBinding(binding);
        log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<< END初始化RabbitMQ的邮箱配置 ========================");
    }

    @Override
    public String sendMsg() {
        Book book = new Book();
        book.setId(1).setName("金瓶梅").setPrice(59.9);
        rabbitTemplate.convertAndSend(ISmsService.MQ_EMAIL_EXCHANGE, ISmsService.MQ_EMAIL_ROUTINGKEY, book);
        return book.toString();
    }


}
